package com.bingxue.edu.migration;

import com.bingxue.edu.common.enums.ClassCategoryEnum;
import com.bingxue.edu.common.enums.ClassStatusEnum;
import com.bingxue.edu.common.enums.JoinTypeEnum;
import com.bingxue.edu.common.enums.SaleStatusEnum;
import com.bingxue.edu.common.enums.StudentClassEnum;
import com.bingxue.edu.common.enums.TermEnum;
import com.bingxue.edu.framework.enums.DictEnums;
import com.bingxue.edu.management.education.model.entity.ClassInfo;
import com.bingxue.edu.management.education.model.entity.ClassStudent;
import com.bingxue.edu.management.education.model.entity.Enrollment;
import com.bingxue.edu.management.education.service.ClassInfoService;
import com.bingxue.edu.management.education.service.ClassStudentService;
import com.bingxue.edu.management.education.service.EnrollmentService;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author panbo
 * @since 2024/10/30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ClassMigrationService {

    private static final String MAIN_DS = "main";
    private static final String LEGACY_DS = "legacy";
    private final ClassInfoService classInfoService;
    private final EnrollmentService enrollmentService;
    private final ClassStudentService classStudentService;

    /**
     * 迁移班级数据，仅限2024年秋季（season=3）
     */
    @Transactional(rollbackFor = Exception.class)
    public void migrationClassInfo() {
        try{
            DataSourceKey.use(LEGACY_DS);
            String sql = """
                select * from edu_class where class_year=2024 and season=3 and is_deleted = 0
            """;
            List<Row> rows = Db.selectListBySql(sql);

            List<ClassInfo> newDataList = rows.stream().map(item -> {
                ClassInfo classInfo = new ClassInfo();
                classInfo.setId(item.getString("id"));
                classInfo.setName(item.getString("name"));
                classInfo.setClassCategory(DictEnums.getByValue(item.getInt("category"), ClassCategoryEnum.class));
                classInfo.setClassYear(item.getLocalDateTime("class_year").getYear());
                classInfo.setTerm(convertTerm(item.getInt("season")));
                classInfo.setGrade(convertGrade(item.getInt("grade")));
                classInfo.setSubject(convertSubject(item.getInt("subject_id")));
                classInfo.setClassTypeId("");
                classInfo.setClassLevelLimit(item.getInt("level"));
                classInfo.setCampusId("");
                classInfo.setClassroomId("");
                classInfo.setLeadTeacherId(item.getString("teacher_id"));
                classInfo.setTotalPrice(item.getBigDecimal("total_price"));
                classInfo.setUnitPrice(item.getBigDecimal("unit_price"));
                classInfo.setPlanStudentCount(item.getInt("planned_count"));
                classInfo.setEnrollStudentCount(item.getInt("enrolled_count"));
                classInfo.setPassedStudentCount(item.getInt("passed_count"));
                classInfo.setLessonChangeLimit(item.getInt("change_limit_count"));
                classInfo.setClassStatus(ClassStatusEnum.COMPLETED);
                classInfo.setSaleStatus(SaleStatusEnum.ON);
                classInfo.setTotalLessonCount(item.getInt("lesson_count"));
                classInfo.setCompletedLessonCount(item.getInt("lesson_count"));
                classInfo.setCreateUser("0");
                classInfo.setCreateTime(item.getLocalDateTime("create_time"));
                classInfo.setUpdateUser("0");
                return classInfo;
            }).toList();
            DataSourceKey.use(MAIN_DS);
            classInfoService.saveBatch(newDataList, 10);
        } finally{
            DataSourceKey.clear();
        }
    }

    private TermEnum convertTerm(Integer season) {
        return switch (season) {
            case 1 -> TermEnum.SPRING;
            case 2 -> TermEnum.SUMMER;
            case 3 -> TermEnum.AUTUMN;
            case 4 -> TermEnum.WINTER;
            default -> null;
        };
    }

    private String convertGrade(Integer grade) {
        return switch (grade) {
            case 1 -> "grade1";
            case 2 -> "grade2";
            case 3 -> "grade3";
            case 4 -> "grade4";
            case 5 -> "grade5";
            case 6 -> "grade6";
            case 7 -> "grade7";
            case 8 -> "grade8";
            case 9 -> "grade9";
            default -> null;
        };
    }

    private String convertSubject(Integer subjectId) {
        return switch (subjectId) {
            case 1 -> "math-xx";
            case 10000000 -> "math-cz";
            case 10000001 -> "physics-xx";
            case 10000002 -> "physics-cz";
            case 10000003 -> "english-xx";
            case 10000004 -> "chinese-xx";
            default -> null;
        };
    }

    //    @Transactional(rollbackFor = Exception.class)
    public void migrationEnrollment() {
        try{
            DataSourceKey.use(LEGACY_DS);
            String sql = """
             select t1.*, t2.lesson_count as lesson_count from edu_enroll_record t1
             left join edu_class t2 on t1.current_class_id = t2.id
              where t1.is_deleted = 0
                and t1.verify_state = 2
                and t2.class_year=2024
                and t2.season=3
             """;
            List<Row> rows = Db.selectListBySql(sql);
            DataSourceKey.use(MAIN_DS);
            int count = rows.size();
            for (int i = 0; i < count; i++) {
                Row item = rows.get(i);
                Enrollment enrollment = new Enrollment();
                enrollment.setStudentId(item.getString("student_id"));
                enrollment.setClassId(item.getString("current_class_id"));
                enrollment.setEnrollLessonCount(12);
                enrollment.setCompletedLessonCount(12);
                enrollment.setCancelLessonCount(0);
                enrollment.setRemainLessonChangeCount(0);
                enrollment.setRemainClassChangeCount(0);
                enrollment.setRemark("1.0导入");
                enrollment.setCreateUser("0");
                enrollment.setCreateTime(item.getLocalDateTime("create_time"));
                enrollment.setUpdateUser("0");
                enrollmentService.save(enrollment);

                ClassStudent classStudent = new ClassStudent();
                classStudent.setEnrollmentId(enrollment.getId());
                classStudent.setStudentId(item.getString("student_id"));
                classStudent.setClassId(item.getString("current_class_id"));
                classStudent.setStudentJoinType(JoinTypeEnum.ENROLL);
                classStudent.setStudentClassStatus(StudentClassEnum.NORMAL);
                classStudent.setRemark("1.0导入");
                classStudent.setCreateUser("0");
                classStudent.setCreateTime(item.getLocalDateTime("create_time"));
                classStudent.setUpdateUser("0");
                classStudentService.save(classStudent);
                System.out.printf("%d/%d%n", i+1, count);
            }
        } finally {
            DataSourceKey.clear();
        }
    }
}
